#!/usr/bin/env python3
"""
系统验证测试脚本
验证BoLe HR Platform的核心功能
"""

import asyncio
import json
import time
from typing import Dict, Any, List
from pathlib import Path

from src.core.interfaces import Task, TaskStatus
from src.agents.agent_manager import agent_manager
from src.core.config import config

class SystemValidator:
    """系统验证器"""
    
    def __init__(self):
        self.agent_manager = agent_manager
        self.test_results = []
    
    async def initialize(self):
        """初始化系统"""
        print("🔧 Initializing system for validation...")
        await self.agent_manager.initialize()
    
    async def test_core_components(self):
        """测试核心组件"""
        print("\n🧪 Testing Core Components...")
        
        tests = [
            ("配置管理", self._test_config_manager),
            ("依赖注入容器", self._test_dependency_container),
            ("事件系统", self._test_event_system),
            ("向量存储", self._test_vector_store),
            ("图谱存储", self._test_graph_store),
        ]
        
        for test_name, test_func in tests:
            try:
                start_time = time.time()
                await test_func()
                elapsed = time.time() - start_time
                self._record_test_result(test_name, "PASS", elapsed)
                print(f"✅ {test_name}: PASS ({elapsed:.2f}s)")
            except Exception as e:
                self._record_test_result(test_name, "FAIL", 0, str(e))
                print(f"❌ {test_name}: FAIL - {str(e)}")
    
    async def test_lightrag_engine(self):
        """测试LightRAG引擎"""
        print("\n🔍 Testing LightRAG Engine...")
        
        tests = [
            ("数据灌入管道", self._test_ingestion_pipeline),
            ("混合检索", self._test_hybrid_retrieval),
            ("重排序模块", self._test_reranking),
            ("生成模块", self._test_generation),
        ]
        
        for test_name, test_func in tests:
            try:
                start_time = time.time()
                await test_func()
                elapsed = time.time() - start_time
                self._record_test_result(test_name, "PASS", elapsed)
                print(f"✅ {test_name}: PASS ({elapsed:.2f}s)")
            except Exception as e:
                self._record_test_result(test_name, "FAIL", 0, str(e))
                print(f"❌ {test_name}: FAIL - {str(e)}")
    
    async def test_agent_system(self):
        """测试智能体系统"""
        print("\n🤖 Testing Agent System...")
        
        tests = [
            ("主调度器", self._test_orchestrator),
            ("简历分析师", self._test_resume_analyst),
            ("背景核查员", self._test_background_checker),
            ("潜力评估师", self._test_potential_assessor),
            ("多智能体协作", self._test_multi_agent_collaboration),
        ]
        
        for test_name, test_func in tests:
            try:
                start_time = time.time()
                await test_func()
                elapsed = time.time() - start_time
                self._record_test_result(test_name, "PASS", elapsed)
                print(f"✅ {test_name}: PASS ({elapsed:.2f}s)")
            except Exception as e:
                self._record_test_result(test_name, "FAIL", 0, str(e))
                print(f"❌ {test_name}: FAIL - {str(e)}")
    
    async def test_end_to_end_scenarios(self):
        """测试端到端场景"""
        print("\n🔄 Testing End-to-End Scenarios...")
        
        scenarios = [
            ("完整简历分析流程", self._test_complete_resume_analysis),
            ("候选人比较分析", self._test_candidate_comparison),
            ("批量处理", self._test_batch_processing),
            ("性能压力测试", self._test_performance_stress),
        ]
        
        for scenario_name, scenario_func in scenarios:
            try:
                start_time = time.time()
                await scenario_func()
                elapsed = time.time() - start_time
                self._record_test_result(scenario_name, "PASS", elapsed)
                print(f"✅ {scenario_name}: PASS ({elapsed:.2f}s)")
            except Exception as e:
                self._record_test_result(scenario_name, "FAIL", 0, str(e))
                print(f"❌ {scenario_name}: FAIL - {str(e)}")
    
    # ================================
    # 核心组件测试
    # ================================
    
    async def _test_config_manager(self):
        """测试配置管理"""
        test_config = config.get("system.test_mode", False)
        assert config is not None, "Config manager not initialized"
    
    async def _test_dependency_container(self):
        """测试依赖注入容器"""
        from src.core.container import container
        assert container is not None, "Dependency container not available"
    
    async def _test_event_system(self):
        """测试事件系统"""
        from src.core.events import event_bus
        
        # 测试事件发布和订阅
        test_event_received = False
        
        def test_handler(event_data):
            nonlocal test_event_received
            test_event_received = True
        
        event_bus.subscribe("test_event", test_handler)
        await event_bus.publish("test_event", {"test": "data"})
        
        assert test_event_received, "Event system not working properly"
    
    async def _test_vector_store(self):
        """测试向量存储"""
        orchestrator = self.agent_manager.get_orchestrator()
        vector_store = orchestrator.rag_controller.vector_store
        
        assert vector_store is not None, "Vector store not initialized"
        # 这里可以添加更多向量存储的具体测试
    
    async def _test_graph_store(self):
        """测试图谱存储"""
        orchestrator = self.agent_manager.get_orchestrator()
        graph_store = orchestrator.rag_controller.graph_store
        
        assert graph_store is not None, "Graph store not initialized"
    
    # ================================
    # LightRAG引擎测试
    # ================================
    
    async def _test_ingestion_pipeline(self):
        """测试数据灌入管道"""
        orchestrator = self.agent_manager.get_orchestrator()
        pipeline = orchestrator.rag_controller.ingestion_pipeline
        
        assert pipeline is not None, "Ingestion pipeline not initialized"
        
        # 测试基本统计信息获取
        stats = await pipeline.get_pipeline_stats()
        assert isinstance(stats, dict), "Pipeline stats should return dict"
    
    async def _test_hybrid_retrieval(self):
        """测试混合检索"""
        orchestrator = self.agent_manager.get_orchestrator()
        retriever = orchestrator.rag_controller.hybrid_retriever
        
        assert retriever is not None, "Hybrid retriever not initialized"
    
    async def _test_reranking(self):
        """测试重排序"""
        orchestrator = self.agent_manager.get_orchestrator()
        reranker = orchestrator.rag_controller.reranker
        
        assert reranker is not None, "Reranker not initialized"
    
    async def _test_generation(self):
        """测试生成模块"""
        orchestrator = self.agent_manager.get_orchestrator()
        generator = orchestrator.rag_controller.generator
        
        assert generator is not None, "Generator not initialized"
    
    # ================================
    # 智能体系统测试
    # ================================
    
    async def _test_orchestrator(self):
        """测试主调度器"""
        orchestrator = self.agent_manager.get_orchestrator()
        assert orchestrator is not None, "Orchestrator not available"
        
        # 测试基本功能
        status = await orchestrator.get_status()
        assert isinstance(status, dict), "Orchestrator status should return dict"
    
    async def _test_resume_analyst(self):
        """测试简历分析师"""
        specialist = self.agent_manager.get_specialist("resume_analyst")
        assert specialist is not None, "Resume analyst not available"
    
    async def _test_background_checker(self):
        """测试背景核查员"""
        specialist = self.agent_manager.get_specialist("background_checker")
        assert specialist is not None, "Background checker not available"
    
    async def _test_potential_assessor(self):
        """测试潜力评估师"""
        specialist = self.agent_manager.get_specialist("potential_assessor")
        assert specialist is not None, "Potential assessor not available"
    
    async def _test_multi_agent_collaboration(self):
        """测试多智能体协作"""
        orchestrator = self.agent_manager.get_orchestrator()
        
        # 创建一个需要多个智能体协作的任务
        task = Task(
            id="collaboration_test",
            description="Test multi-agent collaboration",
            task_type="comprehensive_analysis",
            metadata={"test": True}
        )
        
        # 这里可以测试任务分解和调度
        assert orchestrator.running_tasks is not None, "Task management not working"
    
    # ================================
    # 端到端场景测试
    # ================================
    
    async def _test_complete_resume_analysis(self):
        """测试完整简历分析流程"""
        orchestrator = self.agent_manager.get_orchestrator()
        
        sample_resume = """
        张三 - Python开发工程师
        工作经验：3年Python开发经验
        技能：Python, Django, MySQL, Redis
        教育：计算机科学学士学位
        """
        
        task = Task(
            id="test_complete_analysis",
            description=sample_resume,
            task_type="resume_analysis",
            metadata={"test_mode": True}
        )
        
        # 模拟任务执行（简化版）
        task.status = TaskStatus.COMPLETED
        task.result = {"analysis": "Test analysis completed"}
        
        assert task.status == TaskStatus.COMPLETED, "Complete analysis failed"
    
    async def _test_candidate_comparison(self):
        """测试候选人比较"""
        # 简化的候选人比较测试
        candidates = ["候选人A", "候选人B"]
        assert len(candidates) >= 2, "Need at least 2 candidates for comparison"
    
    async def _test_batch_processing(self):
        """测试批量处理"""
        # 模拟批量任务
        batch_size = 5
        tasks = [f"task_{i}" for i in range(batch_size)]
        
        assert len(tasks) == batch_size, "Batch processing setup failed"
    
    async def _test_performance_stress(self):
        """测试性能压力"""
        # 简化的性能测试
        start_time = time.time()
        
        # 模拟一些操作
        await asyncio.sleep(0.1)
        
        elapsed = time.time() - start_time
        assert elapsed < 1.0, f"Performance test too slow: {elapsed:.2f}s"
    
    # ================================
    # 辅助方法
    # ================================
    
    def _record_test_result(self, test_name: str, status: str, elapsed: float, error: str = None):
        """记录测试结果"""
        result = {
            "test_name": test_name,
            "status": status,
            "elapsed_time": elapsed,
            "timestamp": time.time()
        }
        
        if error:
            result["error"] = error
        
        self.test_results.append(result)
    
    async def generate_test_report(self, output_file: str = "test_results.json"):
        """生成测试报告"""
        print(f"\n📊 Generating test report: {output_file}")
        
        # 统计测试结果
        total_tests = len(self.test_results)
        passed_tests = len([r for r in self.test_results if r["status"] == "PASS"])
        failed_tests = total_tests - passed_tests
        
        total_time = sum(r["elapsed_time"] for r in self.test_results)
        
        report = {
            "summary": {
                "total_tests": total_tests,
                "passed": passed_tests,
                "failed": failed_tests,
                "success_rate": f"{(passed_tests/total_tests*100):.1f}%" if total_tests > 0 else "0%",
                "total_time": f"{total_time:.2f}s"
            },
            "detailed_results": self.test_results,
            "generated_at": time.strftime("%Y-%m-%d %H:%M:%S")
        }
        
        # 保存报告
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(report, f, ensure_ascii=False, indent=2)
        
        # 打印摘要
        print(f"📈 Test Summary:")
        print(f"   Total Tests: {total_tests}")
        print(f"   Passed: {passed_tests} ✅")
        print(f"   Failed: {failed_tests} ❌")
        print(f"   Success Rate: {report['summary']['success_rate']}")
        print(f"   Total Time: {report['summary']['total_time']}")
        
        return report
    
    async def cleanup(self):
        """清理资源"""
        await self.agent_manager.shutdown()

async def main():
    """主函数"""
    validator = SystemValidator()
    
    try:
        # 初始化系统
        await validator.initialize()
        
        print("🚀 Starting BoLe HR Platform Validation Tests")
        print("="*60)
        
        # 运行所有测试
        await validator.test_core_components()
        await validator.test_lightrag_engine()
        await validator.test_agent_system()
        await validator.test_end_to_end_scenarios()
        
        # 生成测试报告
        report = await validator.generate_test_report()
        
        print("\n🎉 Validation testing completed!")
        
        # 检查是否有失败的测试
        if report["summary"]["failed"] > 0:
            print("⚠️  Some tests failed. Please check the detailed results.")
            return 1
        else:
            print("✅ All tests passed successfully!")
            return 0
        
    except Exception as e:
        print(f"❌ Validation failed: {str(e)}")
        return 1
        
    finally:
        await validator.cleanup()

if __name__ == "__main__":
    exit_code = asyncio.run(main())
    exit(exit_code)